package org.zjh.utils;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;

/**
 * @description: 播放音乐工具类
 * @author 郑佳豪
 * @date 2024/10/5 6:37
 * @version 1.0
 */
public class MusicUtil {
    private Clip clip;

    public void playMusic(String filePath) {
        try {
            // 打开音频输入流
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(new File(filePath));

            // 获取音频剪辑对象
            clip = AudioSystem.getClip();
            clip.open(audioStream);

            // 开始播放
            clip.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 停止播放
    public void stopMusic() {
        if (clip != null && clip.isRunning()) {
            clip.stop();
        }
    }

}
